package cn.ac.cintcm.dao.hibernate;

import java.util.List;

import cn.ac.cintcm.dao.TherapyDao;
import cn.ac.cintcm.model.Therapy;

public abstract class TherapyDaoGeneric  extends GenericDaoHibernate<Therapy, Long> implements TherapyDao {

	public TherapyDaoGeneric() {
		super(Therapy.class);
	}

	@SuppressWarnings("unchecked")
	public List<Therapy> getTherapy(String start, String end) {
		String hsql = "from Therapy where tdate between '" + start + "' and '" + end + "'";
		return getHibernateTemplate().find(hsql);
	}

	@SuppressWarnings("unchecked")
	public List<Therapy> getUserTherapy(long uid, String start, String end) {
		String hsql = "from Therapy where patient.id=" + uid + " and tdate between '" + start + "' and '" + end + "'";
		return getHibernateTemplate().find(hsql);
	}

	@SuppressWarnings("unchecked")
	public List<Therapy> getHistoryTherapy(long uid) {
		String hsql = "from Therapy where patient.id=" + uid + " and pid=0 order by tdate desc";
		List<Therapy> therapies = getHibernateTemplate().find(hsql);
		return therapies;
	}

	@SuppressWarnings("unchecked")
	public Therapy getLastTherapy(long uid) {
		String hsql = "from Therapy where patient.id=" + uid+ " order by tdate desc";
		List<Therapy> list = getHibernateTemplate().find(hsql);
		Therapy therapy = new Therapy();
		if (list.size() >0) {
			therapy = list.get(0);
		}
		return therapy;
	}

	@SuppressWarnings("unchecked")
	public List<Therapy> getTherapyThread(long uid, long id) {
		String hsql = "from Therapy where patient.id=" + uid + 
			" and (pid=" + id + " or id=" + id + ") order by tdate asc";
		return getHibernateTemplate().find(hsql);
	}

	@SuppressWarnings("unchecked")
	public List<Therapy> getTherapyByPatient(Long uid) {
		String hsql = "from Therapy where patient.id=" + uid + " order by id tdate";
		List list = getHibernateTemplate().find(hsql);

		return list;
	}

	public Therapy getUnnotifiedTherapyByPatient(Long uid) {
		String hsql = "from Therapy where notify=0 and patient.id=" + uid+ " order by id asc";
		List list = getHibernateTemplate().find(hsql);
		Therapy therapy = null;
		if (list != null && list.size() > 0) {
			therapy = (Therapy) list.get(0);
		}
		return therapy;
	}
	
	public List<Therapy> getDoctorTherapies(String username) {
		String hsql = "from Therapy where doctor.username='" + username + "' order by tdate desc";
		List list = getHibernateTemplate().find(hsql);

		return list;
		
	}
	
	public Therapy save(Therapy t) {
		
        getHibernateTemplate().saveOrUpdate(t);
        getHibernateTemplate().flush();
		return t;
		
	}

}
